package top.chenfu.security.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Auther chenfu
 * @2019/10/29 15:33
 * @Desc
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {

    /**
     * 拿用户认证之后获得的权限和要访问的资源所需的权限进行对比
     *
     * @param authentication 用户具备的角色权限
     * @param o
     * @param collection     当前访问路径需要的权限
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//        if (authentication)
//        遍历要访问资源所需的所有角色
        for (ConfigAttribute attribute : collection) {
            if ("ROLE_LOGIN".equals(attribute.getAttribute())) {
//                判断是否登录，因为用户可能此时还没登录
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new BadCredentialsException("未登录");
                } else {
//                    已经登陆过了，就放行
                    return;
                }
            }
//            遍历用户具备的角色，只要匹配其一就可以访问
            for (GrantedAuthority authority : authentication.getAuthorities()) {
//                匹配，通过！
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
